package com.jeegot.coupon.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeegot.common.exception.JeegotException;
import com.jeegot.core.utils.StrUtils;
import com.jeegot.coupon.entity.Coupon;
import com.jeegot.coupon.entity.CouponCode;
import com.jeegot.coupon.mapper.CouponMapper;
import com.jeegot.coupon.service.ICouponCodeService;
import com.jeegot.coupon.service.ICouponService;
import com.jeegot.entity.User;
import com.jeegot.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 优惠券 服务实现类
 * </p>
 *
 * @author wjun_java@163.com
 * @since 2021-07-10
 */
@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {

	@Autowired
	private ICouponCodeService couponCodeService;

	@Autowired
	private IUserService userService;

	@Override
	@Transactional
	public synchronized void takeCoupon(Long couponId, Long userId) throws Exception {

		User user = userService.getById(userId);
		if(user == null) {
			throw new JeegotException("用户不存在");
		}

		Coupon coupon = getById(couponId);
		if(coupon == null) {
			throw new JeegotException("卡券不存在或已删除");
		}

		if(coupon.getStatus() == 0) {
			throw new JeegotException("卡券已失效");
		}

		QueryWrapper queryWrapper = new QueryWrapper();
		queryWrapper.eq("coupon_id", couponId);
		int takeCount = couponCodeService.count(queryWrapper);
		if(takeCount > coupon.getQuota()) {
			throw new JeegotException("已达到优惠券发放数量上限");
		}

		QueryWrapper ccQuery = new QueryWrapper();
		ccQuery.eq("user_id", userId);
		ccQuery.eq("coupon_id", couponId);

		CouponCode code = couponCodeService.getOne(ccQuery);
		if(code != null) throw new JeegotException("已经领取过该优惠券了");

		code = new CouponCode();
		code.setCouponId(coupon.getId());
		code.setTitle(coupon.getTitle());
		code.setCode(StrUtils.uuid());
		code.setUserId(userId);
		code.setStatus(coupon.getStatus());
		code.setValidTime(LocalDateTime.now());
		couponCodeService.saveOrUpdate(code);

		coupon.setTakeCount(takeCount + 1);
		updateById(coupon);

	}

	@Override
	public List<CouponVo> getUserCoupon(Long userId, Integer status) {
		return couponCodeService.getUserCoupon(userId, status);
	}

	@Override
	public List<CouponVo> getCouponList(Long userId) {
		return getBaseMapper().getCouponList(userId);
	}

}
